package com.xxxx.yebserver.exception;

import com.xxxx.yebserver.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@ControllerAdvice
public class GlobeException{
    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        String msg = ExceptionEnum.FIELD_VALID_EXCEPTION.getMsg();
        List<FieldError> field = e.getBindingResult().getFieldErrors();
        List<String> collect = field.stream().map(item->item.getDefaultMessage()).collect(Collectors.toList());
        if(collect.size() > 0) msg = collect.get(0);
        return R.error(ExceptionEnum.FIELD_VALID_EXCEPTION.getCode(),msg);
    }


    @ResponseBody
    @ExceptionHandler(MyException.class)
    public R myException(MyException e){
        log.error("自定义异常,异常信息：{}",e.getMessage());
        return R.error(e.getCode(),e.getMsg());
    }

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public R myException(Exception e){
        log.error("全局异常：{},异常信息：{}",e.getClass(),e.getMessage());
        return R.error(ExceptionEnum.GLOBE_EXCEPTION.getCode(),e.getMessage());
    }
}
